package com.hcinfos.gsoo.ui;

import java.net.URLEncoder;

import org.json.JSONObject;

import com.alipay.android.app.sdk.AliPay;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.Area;
import com.hcinfos.gsoo.enity.Gift;
import com.hcinfos.gsoo.enity.User;
import com.hcinfos.gsoo.pay.Keys;
import com.hcinfos.gsoo.pay.Rsa;
import com.hcinfos.gsoo.util.DialogUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.util.UtilHttp;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class GiftConfirActivity extends Activity implements OnClickListener {

	private ImageView back_iv;
	private TextView price_tv;

	private Gift gift;

	private ImageView gift_iv;
	private TextView name_tv;
	private TextView inter_tv;
	private TextView info_tv;
	private TextView update_tv;
	private TextView des_tv;
	private TextView note_tv;
	private Button diancai_bt;

	private BitmapUtils bitmapUtils;
	private SharePreferenceUtil util;
	private User user;
	private Dialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_giftconfir);
		dialog = DialogUtil.createProgressDialog(this, "提示", "正在提交中...");

		util = new SharePreferenceUtil(this, "setting");
		back_iv = (ImageView) findViewById(R.id.back_iv);
		back_iv.setOnClickListener(this);
		price_tv = (TextView) findViewById(R.id.price_tv);
		price_tv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

		gift = (Gift) getIntent().getSerializableExtra("gift");
		gift_iv = (ImageView) findViewById(R.id.gift_iv);

		name_tv = (TextView) findViewById(R.id.name_tv);
		inter_tv = (TextView) findViewById(R.id.inter_tv);
		info_tv = (TextView) findViewById(R.id.info_tv);

		update_tv = (TextView) findViewById(R.id.update_tv);
		update_tv.setOnClickListener(this);
		des_tv = (TextView) findViewById(R.id.des_tv);
		note_tv = (TextView) findViewById(R.id.note_tv);
		diancai_bt = (Button) findViewById(R.id.diancai_bt);
		diancai_bt.setOnClickListener(this);

		bitmapUtils = new BitmapUtils(this);
		bitmapUtils.configDefaultLoadingImage(R.drawable.tc_shop_default_logo);// 默认背景图片
		bitmapUtils
				.configDefaultLoadFailedImage(R.drawable.tc_shop_default_logo);// 加载失败图片

		bitmapUtils.display(gift_iv, Urls.url + "/" + gift.getImgUrl());

	}

	private boolean isGiftMode = false;

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		user = (User) util.loadObject("user");

		if (user == null) {
			info_tv.setText("请先登录");
			update_tv.setText("登录");
		} else {

			if (user.getSendAddr1() != null) {
				info_tv.setText("兑换人: " + user.getTaName() + " 地址："
						+ user.getSendAddr1());
				update_tv.setVisibility(View.GONE);
			} else {
				info_tv.setText("请填写详细资料");
				update_tv.setText("修改");
			}

			if (user.getGold() >= gift.getIntegrate()) {
				isGiftMode = true;
				diancai_bt.setText("兑换");
			} else {
				isGiftMode = false;
				diancai_bt.setText("抽奖");
			}
		}
		name_tv.setText("礼品名字: " + gift.getGiftName());
		inter_tv.setText("积分: " + gift.getIntegrate());
		price_tv.setText("￥ " + gift.getPrice());
		des_tv.setText(gift.getIntroduction());
		note_tv.setText(gift.getAttention());
	}

	private Intent intent;

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.back_iv:
			finish();
			break;
		case R.id.diancai_bt:

			if (user == null) {
				Toast.makeText(this, "请先登录!", 500).show();
				intent = new Intent(this, LoginActivity.class);
				startActivity(intent);
				return;
			}
			if (isGiftMode) {
				doExchange();
			} else {
				intent = new Intent(this, ChoujiangActivity.class);
				startActivity(intent);
			}

			break;
		case R.id.update_tv:
			if (user == null) {
				intent = new Intent(this, LoginActivity.class);
				startActivity(intent);
			} else {
				if (user.getSendAddr1() == null) {
					intent = new Intent(this, AddressUpdateActivity.class);
					startActivity(intent);
				}

			}

			break;

		}
	}

	public final int SUBMIT_SUCCESS = 0x2210;
	public final int SUBMIT_FAIL = SUBMIT_SUCCESS + 1;
	public final int RQF_PAY = SUBMIT_SUCCESS + 2;

	private void doExchange() {
		if (gift == null)
			return;
		Area area = (Area) util.loadObject("area");
		if (area == null)
			return;
		LogUtil.d("wxf", "name=" + area.getAreaName() + ",id=" + area.getId());
		dialog.show();
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		params.addBodyParameter("giftRecord.giftId", gift.getId());
		params.addBodyParameter("giftRecord.exchangeUserId", user.getId());
		params.addBodyParameter("giftRecord.diliverAddr", user.getSendAddr1());
		params.addBodyParameter("giftRecord.contact", user.getTaTelphone());
		params.addBodyParameter("giftRecord.contactName", user.getTaName());

		http.send(HttpRequest.HttpMethod.POST, Urls.callnew_submitGiftExchange,
				params, new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						LogUtil.e("wxf", arg0.toString());
						handler.sendEmptyMessage(SUBMIT_FAIL);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {

						try {
							String result = arg0.result;
							LogUtil.d("wxf", "result = " + result);
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							if (state == 200) {
								orderId = obj.getJSONObject("data").getString(
										"orderId");
								price = obj.getJSONObject("data").getDouble(
										"expressFee");
								giftName = obj.getJSONObject("data").getString(
										"giftName");
								handler.sendEmptyMessage(SUBMIT_SUCCESS);
							} else {
								Message message = handler.obtainMessage();
								message.obj = obj.getString("message");
								message.what = SUBMIT_FAIL;
								handler.sendMessage(message);
							}
						} catch (Exception e) {
							handler.sendEmptyMessage(SUBMIT_FAIL);

						}
					}

				});
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			dialog.dismiss();
			switch (msg.what) {
			case SUBMIT_SUCCESS:
				pay();
				break;
			case SUBMIT_FAIL:
				String error = "提交失败!";
				if (msg.obj != null)
					error = msg.obj.toString();
				Toast.makeText(GiftConfirActivity.this, error, 500).show();
				break;
			case RQF_PAY:
				intent = new Intent(GiftConfirActivity.this,
						MyPayActivity.class);
				startActivity(intent);
				finish();
				break;
			}

		};
	};

	private String orderId;
	private double price;
	private String giftName;

	/**
	 * 支付宝支付模块
	 */
	private void pay() {
		String info = getOrderInfo();
		String sign = Rsa.sign(info, Keys.PRIVATE);
		sign = URLEncoder.encode(sign);
		info += "&sign=\"" + sign + "\"&" + getSignType();
		final String orderInfo = info;
		new Thread() {
			public void run() {
				AliPay alipay = new AliPay(GiftConfirActivity.this, handler);

				// 设置为沙箱模式，不设置默认为线上环境
				// alipay.setSandBox(true);
				String result = alipay.pay(orderInfo);
				Message msg = handler.obtainMessage();
				msg.what = RQF_PAY;
				msg.obj = result;
				handler.sendMessage(msg);
			}
		}.start();
	}

	private String getOrderInfo() {
		StringBuilder sb = new StringBuilder();
		sb.append("partner=\"");
		sb.append(Keys.DEFAULT_PARTNER);
		sb.append("\"&out_trade_no=\"");
		sb.append(orderId);
		sb.append("\"&subject=\"");
		sb.append("礼品兑换订单");
		sb.append("\"&body=\"");
		sb.append(giftName);
		sb.append("\"&total_fee=\"");
		sb.append(price + "");
		sb.append("\"&notify_url=\"");

		// 网址需要做URL编码
		sb.append(URLEncoder
				.encode("http://www.gsoo.com/alipaySupport_busi_gift_pay_call_back.action"));
		sb.append("\"&service=\"mobile.securitypay.pay");
		sb.append("\"&_input_charset=\"UTF-8");
		sb.append("\"&return_url=\"");
		sb.append(URLEncoder.encode("http://m.alipay.com"));
		sb.append("\"&payment_type=\"1");
		sb.append("\"&seller_id=\"");
		sb.append(Keys.DEFAULT_SELLER);

		// 如果show_url值为空，可不传
		// sb.append("\"&show_url=\"");
		sb.append("\"&it_b_pay=\"1m");
		sb.append("\"");

		return new String(sb);
	}

	private String getSignType() {
		return "sign_type=\"RSA\"";
	}

}
